package com.seqb.manage.menu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.seqb.common.BuildTree;
import com.seqb.common.Tree;
import com.seqb.common.mybatis.WrapperHandler;
import com.seqb.manage.menu.dao.MenuDao;
import com.seqb.manage.menu.domain.MenuDO;
import com.seqb.manage.menu.service.MenuService;
import com.seqb.manage.role.dao.RoleMenuDao;
import com.seqb.manage.role.domain.RoleMenuDO;
import com.seqb.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/14
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private RoleMenuDao roleMenuDao;

    @Override
    public MenuDO get(Long id) {
        return menuDao.selectById(id);
    }

    @Override
    public Page<MenuDO> list(Map<String, Object> map) {
        if (null != map && null != map.get("pageNumber") && null != map.get("pageSize")) {
            PageHelper.startPage(Integer.valueOf(map.get("pageNumber").toString()), Integer.valueOf(map.get("pageSize").toString()));
        } else {
            PageHelper.startPage(1, Integer.MAX_VALUE);
        }
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, MenuDO.class);
        queryWrapper.orderByAsc("sort_number");
        return (Page<MenuDO>) menuDao.selectList(queryWrapper);
    }

    @Override
    public int count(Map<String, Object> map) {
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, MenuDO.class);
        return menuDao.selectCount(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(MenuDO menu) {
        return menuDao.insert(menu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(MenuDO menu) {
        int update = 0;
        Long id = menu.getId();
        if (null == id) {
            return update;
        }
        String clearField = menu.getClearField();
        if (StringUtils.isEmpty(clearField)) {
            update = menuDao.updateById(menu);
        } else {
            UpdateWrapper updateWrapper = WrapperHandler.genUpdateWrapper(menu);
            updateWrapper.eq("id", id);
            update = menuDao.update(menu, updateWrapper);
        }
        return update;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(Long id) {
        return menuDao.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchRemove(Long[] ids) {
        return menuDao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public Set<String> listPerms(Long userId) {
        List<String> perms = menuDao.listPerms(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotBlank(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public PageUtils menuTree(Long id) {
        try {
            List selectMenuIds = new ArrayList();
            if (null != id) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("role_id", id);
                List<RoleMenuDO> roleMenu = roleMenuDao.selectList(queryWrapper);
                if (null != roleMenu && roleMenu.size() > 0) {
                    for (RoleMenuDO roleMenuDO : roleMenu) {
                        selectMenuIds.add(roleMenuDO.getMenuId());
                    }
                }
            }
            List<Tree<MenuDO>> trees = new ArrayList<Tree<MenuDO>>();
            List<MenuDO> menuList = menuDao.selectList(null);
            for (MenuDO menu : menuList) {
                if (selectMenuIds.contains(menu.getParentId())) {
                    selectMenuIds.remove(menu.getParentId());
                }
            }
            for (MenuDO menuDO : menuList) {
                Tree<MenuDO> tree = new Tree<MenuDO>();
                tree.setId(menuDO.getId().toString());
                tree.setParentId(menuDO.getParentId().toString());
                tree.setTitle(menuDO.getName());
                if (selectMenuIds.contains(menuDO.getId())) {
                    tree.setChecked(true);
                }
                trees.add(tree);
            }
            // 默认顶级菜单为0，根据数据库实际情况调整
            List<Tree<MenuDO>> list = BuildTree.buildList(trees, "0");
            return new PageUtils(list, menuList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Tree<MenuDO>> listTree(Long id) {
        List<Tree<MenuDO>> trees = new ArrayList<Tree<MenuDO>>();
        List<MenuDO> menuList = menuDao.listTree(id);
        for (MenuDO menuDO : menuList) {
            Tree<MenuDO> tree = new Tree<MenuDO>();
            tree.setId(menuDO.getId().toString());
            tree.setParentId(menuDO.getParentId().toString());
            tree.setTitle(menuDO.getName());
            Map<String, Object> attributes = new HashMap<>(16);
            String icon = menuDO.getIcon();
            String url = menuDO.getUrl();
            attributes.put("url", url);
            attributes.put("icon", icon);
            tree.setAttributes(attributes);
            trees.add(tree);
        }
        // 默认顶级菜单为0，根据数据库实际情况调整
        List<Tree<MenuDO>> list = BuildTree.buildList(trees, "0");
        return list;
    }

}
